<?php
class ModelCommunityYourday extends Model{
    public function addName($data){
            $query=$this->db->query("SELECT name_id, nominate_ips FROM " . DB_PREFIX . "community_yourday WHERE LCASE(name)='" . $this->db->escape(utf8_strtolower(trim($data['name']))) . "' LIMIT 0,1");

            if($query->row){
                $ip_str=$query->row['nominate_ips'];
                $ips=explode(',', $ip_str);

                array_push($ips, $this->request->server['REMOTE_ADDR']);

                $ip_str=implode(',', $ips);
            }else{
                $ip_str=$this->request->server['REMOTE_ADDR'];
            }

            if($query->row){
                $this->db->query("UPDATE " . DB_PREFIX . "community_yourday SET nominate_count=nominate_count+1, nominate_ips='" . $this->db->escape($ip_str) . "', last_nominate_time='" . time() . "' WHERE name_id='" . $query->row['name_id'] . "'");

                $name_id=$query->row['name_id'];
            }else{
                $this->db->query("INSERT INTO " . DB_PREFIX . "community_yourday SET name='" . $this->db->escape(utf8_strtolower(trim($data['name']))) . "', nominate_count='1', nominate_ips='" . $this->db->escape($ip_str) . "', last_nominate_time='" . time() . "'");

                $name_id=$this->db->getLastId();
            }

        $this->db->query("INSERT INTO " . DB_PREFIX . "community_yourday_email SET name_id='" . (int)$name_id . "', email='" . $this->db->escape($data['email']) . "'");

        $newsletter_query=$this->db->query("SELECT newsletter_id FROM " . DB_PREFIX . "community_yourday_newsletter WHERE LCASE(email)='" . $this->db->escape(utf8_strtolower($data['email'])) . "' LIMIT 0,1");

        if(isset($data['newsletter']) && !$newsletter_query->row){
            $this->db->query("INSERT INTO " . DB_PREFIX . "community_yourday_newsletter SET email='" . $this->db->escape($data['email']) . "'");
        }
    }

    public function validateName($name){
        $query=$this->db->query("SELECT nominate_ips FROM " . DB_PREFIX . "community_yourday WHERE name='" . $this->db->escape(utf8_strtolower(trim($name))) . "' LIMIT 0,1");

        if($query->row){
            $ip_str=$query->row['nominate_ips'];
            $ips=explode(',', $ip_str);

            if(in_array($this->request->server['REMOTE_ADDR'], $ips)){
                return FALSE;
            }else{
                return TRUE;
            }
        }else{
            return TRUE;
        }
    }

    public function getUpcomingNames(){
        $query=$this->sql_cache->get('community.upcomingnames');

        if(!$query){
            $query=$this->db->query("SELECT * FROM " . DB_PREFIX . "community_yourday WHERE used='0' AND being_displayed='1' ORDER BY upcoming_date ASC");

            $this->sql_cache->set('community.upcomingnames', $query);
        }

        return $query->rows;
    }
}
?>